package com.quectel.mobile.controller;

import com.quectel.sys.module.sys.service.SysGroupService;
import com.quectel.util.common.Response;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

public class BaseController {
    @Autowired
    protected HttpServletRequest httpServletRequest;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @DubboReference
    private SysGroupService sysGroupService;


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response<Object> handleException(Exception e) {
        logger.error("BaseController报警", e);
        if (e instanceof MethodArgumentNotValidException) {
            //post参数校验出错
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            //咱们找其中之一就可以
            if (bindingResult.getFieldError() != null) {
                return Response.error("数据校验不通过");
            }
            return Response.error("校验错误");
        }
        if (e instanceof ConstraintViolationException) {
            //get参数出错
            return Response.error(e.getLocalizedMessage());
        }
        if (e instanceof MethodArgumentTypeMismatchException) {
            //get 参数类型不匹配
            return Response.error("非法的查询参数");
        }
        if (e instanceof RpcException) {
            //dubbo服务者不可用
            return Response.error("服务正在重启，请稍后");
        }

        return Response.customize(500, "服务器好像出了点小问题");
    }

}
